<?php
include_once("$config[webroot]/module/product/includes/plugin_order_class.php");
include_once($config['webroot']."/module/logistics/includes/paperprint_class.php");
include_once ("$config[webroot]/module/product/lang/cn.php");
include("../lang/cn/company_type_config.php");
$order=new order();

if($_GET['type']=='update_print_status' && $_GET['oid']>0){
	//更新订单的打印状态为已打印过
	$sql = "update ".ORDER." set print_status=1 where order_id='$_GET[oid]'";
	$db->query($sql);
	$order->order_log($_GET['oid'],'打印发货单','打印','',$_SESSION['ADMIN_USER']);
	echo '<script>window.onload = function(){window.parent.main.document.location.reload();window.parent.DialogManager.close("sendprint");};</script>';
	die('ok');
}
if($_GET['type']=='update_express_print_status' && $_GET['oid']>0){
	//更新订单的快递打印状态为已打印过,写入打印时间
	$sql = "update ".ORDER." set express_print_status=1,express_print_time='".time()."' where order_id='$_GET[oid]'";
	$db->query($sql);
	$order->order_log($_GET['oid'],'打印快递单','打印','',$_SESSION['ADMIN_USER']);
	die('ok');
}
$paperprint=new paperprint();
$de=$order->shop_orderdetail($_GET['oid']);
if(!$de){die;}
//处理变量
$de['count']=0;
$de['ship_time']=$de['ship_time']?$de['ship_time']:time();
$de['ship_date']=date('Y-m-d',$de['ship_time']);
$de['ship_time']=date('Y-m-d H:i:s',$de['ship_time']);
$de['create_time']=date('Y-m-d H:i:s',$de['order_time']);

foreach ($de['product'] as $key=> $item){
	
	$sql="select `code` from ".SETMEAL. " where id={$item['product_id']} limit 1";
	$db->query($sql);
	$pro_code=$db->fetchRow();
	$de['product'][$key]['code']=$pro_code['code'];
    $de['product'][$key]['other']='';
    $de['count']+=$item['num'];
    //条码
    $sql="select `barcode` from haiou_stock_products where product_sku_id={$item['product_id']} limit 1";
    $db->query($sql);
    $pro_barcode=$db->fetchRow();
    $barcode = $pro_barcode['barcode']?$config['weburl'].'/admin/product_barcode.php?barcode='.$pro_barcode['barcode']:'';
    if($barcode){
    	$barcode = "<img width='130' src=\"{$barcode}\" />";
    }else{
    	$barcode = "";
    }
    $de['product'][$key]['barcode']=$barcode;
}
$de['sum']=number_format($de['cost']+$de['freight'],2);
//
$de['invoices_rise']=$de['invoices']['rise']?$de['invoices']['company']:'个人';
$de['invoices_content']=$lang['icontent'][$de['invoices']['rise']];
$de['invoices_type']=$lang['itype'][$de['invoices']['type']];
$de['other']='';

$de['sender_comp']=$lang['sender_comp'];
$de['sender_name']=$lang['sender_name'];
$de['goods_type']=$lang['goods_type'];
$de['sender_phone']=$lang['sender_phone'];
$de['sender_addr']=$lang['sender_addr'];


$de['ship_comp']='';

/* var_dump($de);
die; */
if($_GET['type']=='sendprint'){
    $paper=$_GET['paper']?$_GET['paper']:'1,2';
    $sql="select sendtpl from ".SENDTPL." where `default`=1 and type in($paper) order by `type` asc";
    $db->query($sql);
    foreach ($se=$db->getRows() as $item){
        $sendtpl.=$item['sendtpl'].'<br/></br/>';
    }
    $ext_style = '';
    if(count($de['product'])>7){
    	$ext_style = '.product_table{min-height:1000px;}
    			.shopping_tip{min-height:1000px;}';
    }
    //订单条码
    $order_barcode = $de['order_id']?$config['weburl'].'/admin/product_barcode.php?barcode='.$de['order_id'].'&type=code128&notneednum=1':'';
    if($order_barcode){
    	$order_barcode = "<img width='150' src=\"{$order_barcode}\" />";
    }else{
    	$order_barcode = "";
    }
    $de['order_id_barcode'] = $order_barcode;
    
    //判断是否为分销订单
    if($de['member_id']==645){
    	$de['order_type'] = "(分)";
    }else{
    	$de['order_type'] = "";
    }
    
    echo '<style>'.'html {margin:0;padding:0;}
body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;padding:5px;}
body, p, div {word-wrap: break-word;}
.custom_list{min-height:1100px;}
    		'.$ext_style.'
p {margin:5px 0;}
table {border-collapse:collapse;}
img {border:0;}
noscript {display:none;}input[type="button"]{
    background: url("../image/admin/dialog_button.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    border: 0 none;
    color: #FFFFFF;
    cursor: pointer;
    font-weight: bold;
    height: 26px;
    margin: 7px 0 3px;
    text-align: center;
    width: 70px;
}'.'</style>';
    echo $paperprint->sendprint($de, $sendtpl);
    echo '<br/><br/>';
    echo '<center id="printCtr">只打<input type="text" id="paper" value="'.$paper.'" style="width:50px;">联 &nbsp; <input type="button" value="确定" onclick="location.href=location.href+\'&paper=\'+document.getElementById(\'paper\').value"> &nbsp; <input type="button" id="printBtn" value="打印" onclick="printArea();"></center>';
    echo '<script>function printArea(){document.getElementById("printCtr").style.display="none";window.print();if(confirm("打印完成？")){document.getElementById("printCtr").style.display="block";window.location.href="'.$config[weburl].'/admin/module.php?m=logistics&s=print.php&type=update_print_status&oid='.$de['order_id'].'";}else{printArea()}}</script>';
    die;
}
elseif($_GET['type']=='expressprint'){
    $isGetContent = 0;//是否只获取内容，不要“打印”按钮
    if($_GET['isGetContent']){
        $isGetContent = 1;
    }
    if($_GET['ship_name']!=''){//收货人
        $de['ship_name'] = $_GET['ship_name'];
    }
	//订单号条码
	$order_barcode = $de['order_id']?$config['weburl'].'/admin/product_barcode.php?barcode='.$de['order_id'].'&type=code128':'';
	if($order_barcode){
		$order_barcode = "<img width='150' src=\"{$order_barcode}\" />";
	}else{
		$order_barcode = "";
	}
	$de['order_id_barcode'] = $order_barcode;
	//运单号条码
	$shipping_no_barcode = $de['shipping_no']?$config['weburl'].'/admin/product_barcode.php?barcode='.$de['shipping_no'].'&type=code128&is_str=1':'';
	if($shipping_no_barcode){
		$shipping_no_barcode = "<img width='200' src=\"{$shipping_no_barcode}\" />";
	}else{
		$shipping_no_barcode = "";
	}
	$de['shipping_no_barcode'] = $shipping_no_barcode;

	$de['sender_name'] = $company_information[$de['stock_shop']]['name'];
	$de['sender_phone'] = $company_information[$de['stock_shop']]['tel'];
	$de['sender_addr'] = $company_information[$de['stock_shop']]['addr'];
	$de['count'] = 1;
	$de['payment_name'] = "";//付款方式
	$de['return_decimal_price'] = "";//保价金额
	$de['picking_goods_info'] = "";//配货信息
	
	if(!($de['shipping_express_id']>0)){
	    die('未选择快递！');
	}
    $sql="select sign from ".FASTMAIL." where id=$de[shipping_express_id]";
    $db->query($sql);
    $tmp=$db->fetchRow();
    $expresstpl=($tmp['sign']);
    if (empty($expresstpl))die;
    if (!file_exists($tpl->template_dir.'/'.$expresstpl.'.html'))die('模板不存在');
    
    $tpl->assign("config",$config);
    $tpl->assign("isGetContent",$isGetContent);
    $tpl->assign('expresstpl',$expresstpl);
    $tpl->assign('de',$de);
    $out=tplfetch($expresstpl.".html",null);
    echo $paperprint->expressprint($de, $out);
    die;
    
}
elseif($_GET['type']=='purchasePrint'){
	$de = array();
	$de['product'] = array();
	$purchaseId = empty($_GET['purchaseid']) ? 0 : intval($_GET['purchaseid']);
	if(isset($_GET['uri']) && $_GET['uri']=='orderProducts'){
		$supplier = "";
		$shop = "";
		$where = "";
		$storeWhere = "";
			if($_GET['shopid']>0){
				$where .= " AND `hso`.`shopid`='{$_GET['shopid']}'";
			}else{
				$_GET['shopid'] = 1;
				$where .= " AND `hso`.`shopid`='1'";
			}
			$sql = "select title from haiou_stock_shops where id='{$_GET['shopid']}'";
			$db->query($sql);
			$shop = $db->fetchField('title');
			
			if(!$_GET['listType']){
				$_GET['listType'] = 2;
			}
// 			if($_GET['classid']>0){
// 				$where .= " AND `hsp`.`classid`='{$_GET['classid']}' ";
// 			}
			if($_GET['supplierid']>0){
				$sql = "select title from haiou_stock_suppliers where id='{$_GET['supplierid']}'";
				$db->query($sql);
				$supplier = $db->fetchField('title');
				$where .= " AND FIND_IN_SET('{$_GET['supplierid']}',`hsp`.`supplieid`)";
				$storeWhere .= " AND FIND_IN_SET('{$_GET['supplierid']}',`hsp1`.`supplieid`)";
			}
			if($_GET['sdate']){
				$sdate = strtotime($_GET['sdate']." 00:00:00");
				$where .= " AND `hso`.`thedate`>{$sdate}";
			}
			if($_GET['edate']){
				$edate = strtotime($_GET['edate']." 23:59:59");
				$where .= " AND `hso`.`thedate`<{$edate}";
			}
			
			$sql = "SELECT `hso`.`productid` AS `resultId`,SUM(`hso`.`number`) AS `number` FROM
			`haiou_stock_orders` AS `hso`
			LEFT JOIN `haiou_stock_products` AS `hsp` ON `hsp`.`product_sku_id`=`hso`.`productid`
			WHERE (`hso`.`type`=0 or `hso`.`type`=5) {$where} AND `hso`.`timestocked`=0
			GROUP BY `hso`. `productid`
			HAVING `number`>(
			(SELECT IFNULL((SELECT `stocks` FROM `haiou_stock_stocks` AS `Shss` WHERE `Shss`.`productid`=`resultId` and `Shss`.shopid={$_GET['shopid']}),0))
			+
			(SELECT IFNULL((SELECT SUM(`SShsp`.`number`) FROM `haiou_stock_purchases` AS `SShsp` WHERE `SShsp`.`productid`=`resultId` AND `SShsp`.shopid={$_GET['shopid']} AND `timeexpress`=0  GROUP BY(`SShsp`.`productid`)),0))
			)
			";

			$db->query($sql);
			$orderProducts = $db->getRows();//订单采购
			
			if($_GET['listType']==1){
				//备货采购
				$sql = "SELECT `hsp1`.`product_sku_id` AS `resultId`,`hsp1`.`shopwarningnum`,IFNULL(`hss`.`stocks`,0) AS stock,(SELECT IFNULL((SELECT SUM(`hso`.`number`) FROM `haiou_stock_orders` AS `hso` LEFT JOIN `haiou_stock_products` AS `hsp` ON `hsp`.`product_sku_id`=`hso`.`productid` WHERE `hso`.`productid`=`hsp1`.`product_sku_id` AND `hso`.`timestocked`=0 {$where}),0)) AS order_num
				FROM `haiou_stock_products` AS	`hsp1`
				LEFT JOIN `haiou_stock_stocks` AS `hss` ON `hsp1`.`product_sku_id`=`hss`.`productid` AND `hss`.`shopid`={$_GET['shopid']}
				LEFT JOIN `haiou_product_sku` AS `hps` ON `hps`.`id`=`hsp1`.`product_sku_id`
				WHERE `hsp1`.`shopid`={$_GET['shopid']} AND `hps`.`status`>0 {$storeWhere}
				HAVING (stock-order_num+(SELECT IFNULL((SELECT SUM(`SShsp`.`number`) FROM `haiou_stock_purchases` AS `SShsp` WHERE `SShsp`.`productid`=`hsp1`.`product_sku_id` AND `SShsp`.shopid={$_GET['shopid']} AND `timeexpress`=0  GROUP BY(`SShsp`.`productid`)),0)))<`hsp1`.`shopwarningnum`";
				
				$db->query($sql);
				$storeProducts = $db->getRows();
				
				$sql = "select `sku_id` as `resultId`,sum(`num`) as totalNum from ".MICROSTOCK." where stock_shop='{$_GET['shopid']}' GROUP BY sku_id HAVING totalNum>0";
				$db->query($sql);
				$microStockProducts = $db->getRows();//微仓采购
				
				if(empty($orderProducts) && empty($storeProducts) && empty($microStockProducts)){
					exit;
				}
			}else{
			    $sql = "select `sku_id` as `resultId`,sum(`num`) as totalNum from ".MICROSTOCK." where stock_shop='{$_GET['shopid']}' GROUP BY sku_id HAVING totalNum>0";
			    $db->query($sql);
				$microStockProducts = $db->getRows();//微仓采购
			    
				if(empty($orderProducts) && empty($microStockProducts)){
					exit;
				}
			}
			//订单采购
			$needProducts = array();
			$microStockNeedProducts = array();
			$productsIdStr = '';
			if($_GET['listType']==2){
    			//订单采购
    			foreach($orderProducts as $v){
    				if($productsIdStr!=''){
    					$productsIdStr .= ',';
    				}
    				$productsIdStr .= $v['resultId'];
    				$needProducts[$v['resultId']] = $v['number'];
    			}
    			if(!empty($microStockProducts)){
    			    foreach($microStockProducts as $mv){
    			        if(empty($needProducts[$mv['resultId']])){
    			            if($productsIdStr!=''){
    			                $productsIdStr .= ',';
    			            }
    			            $productsIdStr .= $mv['resultId'];
    			        }
    			        $microStockNeedProducts[$mv['resultId']] = $mv['totalNum'];
    			    }
    			}
			}
			if($_GET['listType']==1){//备货采购
				if(!empty($storeProducts)){
					foreach($storeProducts as $sv){
						if(empty($needProducts[$sv['resultId']])){
							if($productsIdStr!=''){
								$productsIdStr .= ',';
							}
							$productsIdStr .= $sv['resultId'];
							$needProducts[$sv['resultId']] = $sv['order_num'];
						}
					}
				}
				if(!empty($microStockProducts)){
				    foreach($microStockProducts as $mv){
				        if(empty($needProducts[$mv['resultId']])){
				            if($productsIdStr!=''){
				                $productsIdStr .= ',';
				            }
				            $productsIdStr .= $mv['resultId'];
				        }
				        $microStockNeedProducts[$mv['resultId']] = $mv['totalNum'];
				    }
				}
			}
			
		$sql = "SELECT hps.id,hps.pid,hps.pname,hps.price,hps.spec,hps.pic,hps.`status`,hps.code,hsp.pricebuy AS cost_price,hsp.barcode,IFNULL(`hss`.`stocks`,0) AS `stocks`,`hpc`.`cat` as cat_name,`hsp`.`shopwarningnum`,`hsp`.`currency_unit`
		FROM haiou_product_sku AS hps
		LEFT JOIN haiou_stock_products AS `hsp` ON `hsp`.`product_sku_id`=`hps`.`id`
		LEFT JOIN `haiou_stock_stocks` AS `hss` ON `hss`.`productid`=`hps`.`id` and `hss`.shopid={$_GET['shopid']}
		LEFT JOIN `haiou_product_cat` AS `hpc` ON `hps`.`catid`=`hpc`.`catid`
		where `hps`.`id` IN({$productsIdStr}) ORDER BY `pid` DESC";
		$db->query($sql);
		$result = $db->getRows();
		//计算库存差值
		$sql = "SELECT `productid`,SUM(`number`) AS `number` FROM `haiou_stock_purchases` WHERE `productid`  IN({$productsIdStr}) AND `shopid`={$_GET['shopid']} AND `timeexpress`=0 GROUP BY(`productid`)";
		$db->query($sql);
		$resultPurchases = $db->getRows();
		$purchases = array();
		foreach($resultPurchases as $v){
			$purchases[$v['productid']] = $v['number'];
		}
		foreach($result as $k=>$v){
				$purchases[$v['id']] = empty($purchases[$v['id']])?0:$purchases[$v['id']];
				$shopwarningnum = ($v['status']<=0)?0:$v['shopwarningnum'];
				$result[$k]['number'] = $needProducts[$v['id']] - $v['stocks'] - $purchases[$v['id']] + $shopwarningnum;
				$order_num = $needProducts[$v['id']] - $v['stocks'] - $purchases[$v['id']];
				
				$result[$k]['order_num'] = ($order_num>=0)?$order_num:0;
				$result[$k]['warningNum'] = ($result[$k]['number']>0?$result[$k]['number']:0) - $result[$k]['order_num'];
				$result[$k]['microStockNeedNum'] = empty($microStockNeedProducts[$v['id']])?0:$microStockNeedProducts[$v['id']];
				$leftStocks = ($v['stocks'] + $purchases[$v['id']] - $shopwarningnum - $needProducts[$v['id']]);
				$result[$k]['microStockNum'] = ($leftStocks>0)?$result[$k]['microStockNeedNum']-$leftStocks:$result[$k]['microStockNeedNum'];
				$result[$k]['number'] = $result[$k]['number']+$result[$k]['microStockNeedNum'];
		}
		//拆分图片
		$resArr = array();
		foreach($result as $k=>$v)
		{
				$picArr = explode(',', $v['pic']);
				$v['pic'] = $picArr[0];
				if($v['number']>0){
				    $resArr[$k] = $v;
				}
		}
		

		$sumPrice = 0;
		foreach ($resArr as $item){
			if(empty($de['product'])){
				$de['name'] = date("Y-m-d_H-i-s",time())."_order_products";
				$de['shop'] = $shop;
				$de['supplier'] = $supplier;
				$de['writer_date'] = date('Y-m-d H:i:s',time());
				$de['puser'] = $_SESSION['ADMIN_USER'];
				$de['other'] = '';
				$de['purchase_express_money'] = 0;
				$de['purchase_discount_money'] = 0;
				$de['purchase_other_money'] = 0;
				$de['currency_unit'] = $item['currency_unit'];
			}
			$sum = $item['number']*$item['cost_price'];
			//生成条码图
			$barcode = $item['barcode']?$config['weburl'].'/admin/product_barcode.php?barcode='.$item['barcode']:'';
			if($barcode){
				$barcode = "<img width='130' src=\"{$barcode}\" />";
			}else{
				$barcode = "";
			}
			//采购数量
			$num = "订单: ".($item['order_num']*1)." 个<br/>微仓: ".($item['microStockNum']*1)."个<br/>预警: ".($item['warningNum']*1)." 个<br/>总数: ".$item['number']." 个";
			$de['product'][] = array(
					'id'=>$item['pid'],
					'barcode'=>$barcode,
					'cat_name'=>$item['cat_name'],
					'code'=>$item['code'],
					'pic'=>"<img src=\"{$item['pic']}/80\" />",
					'name'=>$item['pname'],
					'num'=>$num,
					'price'=>$item['cost_price']*1,
					'spec'=>$item['spec'],
					'unit'=>$item['unit'],
					'sum'=>$sum,
			);
			$sumPrice += $sum;
		}
		$de['purchase_total_money'] = $sumPrice;
	}else{
		if($purchaseId<=0) {
			exit;
		}
		$sql = "SELECT `hps`.`code`,`hspp`.`id` as paper_id,`hspp`.`title`,`hspp`.`shop`,`hspp`.`supplier`,`hspp`.`create_time`,`hspp`.`create_time`,`hspp`.`memo`,`hspp`.`puser`,
					`hsp`.`unit`,`hsp`.`pricebuy`,`hsp`.`number`,`hsp`.`discount`,`hspp`.`purchase_price`,`hspp`.`other_price`,`hspp`.`discount_price`,`hspp`.`express_price`,
					`hps`.`id`,`hps`.`pname`,`hps`.`spec`,`hps`.`pic`,`hsps`.`barcode`,`hpc`.`cat` as cat_name,`hspp`.`currency_unit` 
					FROM `haiou_stock_purchases_paper` AS `hspp` 
					LEFT JOIN `haiou_stock_purchases` AS `hsp` ON `hsp`.`paper_id`=`hspp`.`id` 
					LEFT JOIN `haiou_product_sku` AS `hps` ON `hps`.`id`=`hsp`.`productid` 
					LEFT JOIN `haiou_stock_products` AS `hsps` ON `hsps`.`product_sku_id`=`hsp`.`productid` 
					LEFT JOIN `haiou_product_cat` AS `hpc` ON `hps`.`catid`=`hpc`.`catid` 
					WHERE `hspp`.id=$purchaseId order by `hsp`.id asc";
		$db->query($sql);
		if($db->num_rows()<=0){
			exit;
		}
		$sumPrice = 0;
		$de['currency_unit'] = "";
		foreach ($se=$db->getRows() as $item){
			if(empty($de['product'])){
				$de['name'] = $item['title'];
				$de['shop'] = $item['shop'];
				$de['supplier'] = $item['supplier'];
				$de['writer_date'] = $item['create_time'];
				$de['puser'] = $item['puser'];
				$de['other'] = $item['memo'];
				$de['purchase_express_money'] = $item['express_price'];
				$de['purchase_discount_money'] = $item['discount_price'];
				$de['purchase_other_money'] = $item['other_price'];
				$de['purchase_total_money'] = $item['purchase_price'];
				$de['currency_unit'] = $item['currency_unit'];
			}
			$picArr = explode(',', $item['pic']);
			$sum = $item['number']*$item['pricebuy'];
			//生成条码图
			$barcode = $item['barcode']?$config['weburl'].'/admin/product_barcode.php?barcode='.$item['barcode']:'';
			if($barcode){
				$barcode = "<img width='130' src=\"{$barcode}\" />";
			}else{
				$barcode = "";
			}
			$de['product'][] = array(
							'id'=>$item['id'],
							'barcode'=>$barcode,
							'cat_name'=>$item['cat_name'],
							'code'=>$item['code'],
							'pic'=>"<img src=\"{$picArr[0]}/80\" />",
							'name'=>$item['pname'],
							'num'=>$item['number']*1,
							'price'=>$item['pricebuy']*1,
							'spec'=>$item['spec'],
							'unit'=>$item['unit'],
							'sum'=>$sum,
			);
			$sumPrice += $sum;
			$sendtpl.=$item['sendtpl'];
		}
	}
	$de['total_price'] = $sumPrice;
	$de['purchase_no'] = $item['paper_id']?$item['paper_id']:0;
	
	$paper=$_GET['paper']?$_GET['paper']:'4';
    $sql="select sendtpl from ".SENDTPL." where `default`=1 and type in($paper) order by `type` asc";
    $db->query($sql);
    foreach ($se=$db->getRows() as $item){
    	$sendtpl.=$item['sendtpl'].'<br/></br/>';
    }
    echo '<style>'.'html {margin:0;padding:0;}
body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;padding:5px;}
body, p, div {word-wrap: break-word;}
p {margin:5px 0;}
table {border-collapse:collapse;}
img {border:0;}
noscript {display:none;}input[type="button"]{
    background: url("../image/admin/dialog_button.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    border: 0 none;
    color: #FFFFFF;
    cursor: pointer;
    font-weight: bold;
    height: 26px;
    margin: 7px 0 3px;
    text-align: center;
    width: 70px;
}'.'</style>';
    echo $paperprint->sendprint($de, $sendtpl);
    echo '<br/><br/>';
    echo '<center id="printCtr">只打<input type="text" id="paper" value="'.$paper.'" style="width:50px;">联 &nbsp; <input type="button" value="确定" onclick="location.href=location.href+\'&paper=\'+document.getElementById(\'paper\').value"> &nbsp; <input type="button" id="printBtn" value="打印" onclick="printArea();"></center>';
    echo '<script>function printArea(){document.getElementById("printCtr").style.display="none";window.print();if(confirm("打印完成？")){document.getElementById("printCtr").style.display="block";}else{printArea()}}</script>';
    die;
}

?>